define(['require', '../components/BaseView', './PageView','backbone'], function(require, BaseView, PageView, Backbone){
  return BaseView.extend({

    type: "NavigationView",

    initialize: function(options){
      BaseView.prototype.initialize.apply(this, arguments);
      this.rootPage = options.rootPage;
      // stack to store the views, [{path: 'a', view: a}, {path: 'b', view: b}]
      this.stack = [];
      // 滑出页
      this.currentSliderPage = null;
      // trace the pause and resume state

    },

    render: function(){

      return this;
    },

    remove: function(){
      BaseView.prototype.remove.apply(this, arguments);
    },
    /**
     * 栈顶的页面调用其onPause方法
     */
    onPause: function() {
      if (this.stack.length > 0) {
        var topView = this.stack[this.stack.length - 1].view;
        topView && topView.onPause && topView.onPause();
      }
    },
    /*
     * 栈顶的页面调用其onResume方法
     */
    onResume: function() {
      if (this.stack.length > 0) {
        var topView = this.stack[this.stack.length - 1].view;
        topView && topView.onResume && topView.onResume();
      }
    },

    /**
     * 分析路径
     * @param  {String} path 全路径
     * @return {Object}      {current: 当前路径, remains: 剩余未消化的路径}
     */
    getPaths: function(path){
      var segments = path.split('/');
      // 所有可能的页面路径
      // 例如path为：a/b/c，那么可能的路径（paths）有：['a/b/c', 'a/b', 'a']
      // 从长到短排序
      var paths = segments.map(function(each, index){
        return segments.slice(0, index + 1).join('/');
      }).reverse();
      // 查找匹配的路径，最长路径优先
      var current_path = _.find(paths, function(each){
        return loader.hasPage(each);
      });
      if (current_path == null) {
        alert("page not exists.");
        return {};
      }
      // 剩余路径
      var remains_path = path.slice(current_path.length + 1);

      return {current: current_path, remains: remains_path};
    },
    /**
     * 上左下右各个滑出方向对应的样式产生器
     */
    transitionFactory: {
      "leftOut": {
        "slideInitTransform": function(windowWidth){
          return "translate3d(" + ( 0 - windowWidth ) + "px,0,0)";
        },
        "slideEndTransform": function(stretchConfig){
          return "translate3d(0,0,0)";
        },
        "nomalPageEndTransforom":function(stretchConfig){
          return "translate3d(" + ( stretchConfig.value + "" + stretchConfig.type ) + ",0,0)";
        }
      },
      "rightOut":{
        "slideInitTransform": function(windowWidth){
          return "translate3d(" + (windowWidth) + "px,0,0)";
        },
        "slideEndTransform": function(stretchConfig){
          stretchConfig.value = window.innerWidth - stretchConfig.value;
          return "translate3d(" + ( stretchConfig.value + "" + stretchConfig.type ) + ",0,0)";
        },
        "nomalPageEndTransforom": function(stretchConfig){
          stretchConfig.value = stretchConfig.value - window.innerWidth;
          return "translate3d(" + (stretchConfig.value + "" + stretchConfig.type) + ",0,0)";
        }
      },
      "bottomOut":{
        "slideInitTransform": function(){ return "translate3d(0,100%,0)"; },
        "slideEndTransform": function(){
          return "translate3d(0,0,0)";
        },
        "nomalPageEndTransforom": function(stretchConfig){
          return "translate3d(" + ( stretchConfig.value + "" + stretchConfig.type) + ",0,0)";
        }
      },
      "topOut":{
        "slideInitTransform": function(){return "translate3d(0,-100%,0)";},
        "slideEndTransform": function(){
          return "translate3d(0,0,0)";
        },
        "nomalPageEndTransforom": function(stretchConfig){
          return "translate3d(" + ( stretchConfig.value + "" + stretchConfig.type ) + ",0,0)";
        }
      }
    },
    // 处理滑入页的过渡效果
    pageSlideIn: function(sliderPage, normalPage, transitionConfig){
      var windowWidth = window.innerWidth;
      var transitionType = this.transitionFactory[transitionConfig.type] || this.transitionFactory["leftOut"];
      //stretch转成px
      var pageWidth = transitionConfig.stretch || "100%";
      var duration = transitionConfig.duration;
      var pageWidth_int = parseInt(pageWidth);
      var pxWidth = windowWidth;
      if(!isNaN(pageWidth_int)){
        var pageWidth_str = pageWidth_int.toString();
        var lendiff = pageWidth.length - pageWidth_str.length;
        if(lendiff==1 ){//为百分比
          pxWidth = windowWidth * pageWidth_int / 100;
        }else if(lendiff == 2){
          pxWidth = pageWidth_int;
        }else{
        }
      }
      var stretchConfig = { value : pxWidth , type : "px" };//or px
      var stretch = transitionConfig.stretch;// todo convert stretch to stretchConfig

      sliderPage.$el.css({ "transition":"none","-webkit-transition":"none","transform": transitionType.slideInitTransform(windowWidth) });
      window.setTimeout(function(){
        sliderPage.$el.css({ "transition":"all "+duration+" ease","-webkit-transition":"all " + duration + " ease","transform": transitionType.slideEndTransform(stretchConfig) });
        if(transitionConfig.type == "leftOut" || transitionConfig.type == "rightOut"){
          var normalPage_transform = transitionType.nomalPageEndTransforom(stretchConfig);
          //winkey 直接滑出时 normalPage 不存在（预览）
          normalPage && normalPage.$el.css({ "transition":"all " + duration + " ease","-webkit-transition":"all " + duration + " ease","transform": normalPage_transform });
          Backbone.$('nav.bar').css({ "transition":"all "+duration+" ease","-webkit-transition":"all " + duration + " ease","transform": normalPage_transform });
        }
      },5);
      sliderPage.$el.css({"zIndex":"11"});
      //创建遮罩层
      var sliderBackCover = $("<div class='slide-backover'></div>");
      this.$el.append(sliderBackCover);
      sliderPage.sliderBackCover = sliderBackCover;
      sliderBackCover.bind("click",function(){
          window.history.go(-1);
      });

      this.currentSliderPage = sliderPage;
    },
    // 处理滑出页过渡效果
    pageSlideOut:function(sliderPage, normalPage, transitionConfig){
      var transitionType = this.transitionFactory[transitionConfig.type] || this.transitionFactory["leftOut"];
      var duration = transitionConfig.duration;
      sliderPage.listenOneTransitionEnd(function(){
        sliderPage.remove();
        sliderPage.sliderBackCover.remove();
      });
      if(transitionConfig.type == "leftOut" || transitionConfig.type == "rightOut"){
        normalPage.$el.css({ "transition":"all " + duration + " ease", "-webkit-transition":"all " + duration + " ease", "transform":"translate3d(0,0,0)" });
        Backbone.$('nav.bar').css({ "transition":"all " + duration + " ease","-webkit-transition":"all " + duration + " ease", "transform":"translate3d(0,0,0)" });
      }
      sliderPage.$el.css({ "transition":"all " + duration + " ease", "-webkit-transition":"all " + duration + " ease", "transform": transitionType.slideInitTransform(window.innerWidth)});
    },

    route: function(path, queryString){
      if(this.currentSliderPage){
        this.currentSliderPage.sliderBackCover && this.currentSliderPage.sliderBackCover.remove();
      }
      // 配置的默认页面
      path = path || this.options.rootPage;

      if (!path) {
        console.warn('NavigationView: no path provided.');
        return;
      }

      var paths = this.getPaths(path);
      if (!paths.current) {
        console.warn('page not exists.');
        return;
      }
      console.log("NavigationView: current path: [%s], rest path: [%s]", paths.current, path.remains);

      // FIXME 单纯使用-2来判断不足以判断是否是回退，有可能直接进的详情页，然后再回退 -_-!!!
      // TODO 考虑使用一个结构来记录和追踪进入之前的页面，然后判断是否是回退，此时才使用回退逻辑
      // 是否回退
      var goingBack = this.stack.length > 1 && this.stack[this.stack.length - 2].path == path;

      // 当前页面，栈顶
      var currentPage = this.stack[this.stack.length - 1] && this.stack[this.stack.length - 1].view;
      Backbone.$('nav.bar').css({"transform": "translate3d(0,0,0)"});

      // 获取返回的页面
      var backPage;
      if (goingBack) {
        backPage = this.stack[this.stack.length - 2].view;
      }

      // 当返回页为不缓存页面，不管栈重新创建
      if (goingBack && backPage && !backPage.options.nocache) {
        // 回退
        //console.log(currentPage.sliderBackCover);
        var currentPage_transition = currentPage.options.transition;
        // 调用当前页的onPause,必须发生在remove之前
        currentPage && currentPage.onPause && currentPage.onPause();
        //
        if(currentPage_transition){
          this.pageSlideOut(currentPage,backPage,currentPage_transition);
        }else{
          if(this.options.animate) {
            currentPage.$el.addAnimate('slideOutRight')
            .then(function(){
              currentPage.remove();
            });
            backPage.$el.addAnimate('slideInLeft');
          } else {
            currentPage.remove();
            backPage.$el.show();
          }

        }
        this.stack.pop();
        // 出栈的也重新执行路由
        backPage.route && backPage.route(path.remains, queryString);
        // 从缓存中提取的页面也重新填充数据等，此时dom是准备好的
        backPage.onResume && backPage.onResume();
        //bind to self varialble
        window.self = backPage;

      } else {
        // not always push to stack, check the last page
        if (this.stack.length == 0 || this.stack[this.stack.length - 1].path != paths.current) {
          // 追加
          loader.createPage(paths.current).then(function(nextPage){
            if (!nextPage) {
              console.log("cann't create page:" + paths.current);
              return;
            }
            // 调用当前页的onPause，在slide时可能remove，所以必须在remove发生之前调用
            currentPage && currentPage.onPause && currentPage.onPause();
            // slide out current slide page
            if (currentPage && currentPage.options) {
              var currentPage_transition = currentPage.options.transition;
              if (currentPage_transition) {
                // FIXME it's no sense just for placeholder
                var normalPage = nextPage;
                // this page at index -2 is the normal page
                if (this.stack.length > 1) {
                  normalPage = this.stack[this.stack.length - 2].view;
                }
                this.pageSlideOut(currentPage, normalPage, currentPage_transition);
                this.stack.pop(); // also delete from stack
              }
            }

            var nextpage_options = nextPage.options;
            var nextpage_transition = nextpage_options.transition;
            // assurance, don't let the stack too large, only keep the last three
            // max 50 items in the stack, only keep last 10 items
            if (this.stack.length > 50) {
              this.stack = this.stack.slice(-10);
              this.$el.empty(); //FIXME may be re-render the page in the stack?
            }
            // 消化剩余路由
            // 带模板的页面由于可异步加载模板，所以此时无法保证dom已经准备好了
            nextPage.route && nextPage.route(path.remains, queryString);
            // 填充数据的场景，由于render的过程是可能是异步的,注册一个事件触发
            nextPage.onResume && nextPage.once('domReady', nextPage.onResume.bind(nextPage));
            // 渲染页面
            this.$el.append(nextPage.render().el);
            // bind current page to window.self
            window.self = nextPage;

            if (nextpage_transition) {
              this.pageSlideIn(nextPage,currentPage,nextpage_transition);
            } else {
              if (currentPage && this.options.animate) {
                currentPage.$el.addAnimate('slideOutLeft');
                nextPage.$el.addAnimate('slideInRight');
              } else {
                currentPage && currentPage.$el.hide();
              }
            }
            // 当前页不缓存，移除DOM
            if (currentPage && currentPage.options.nocache) {
                currentPage.$el.remove();
                this.stack.pop();
            }
            // 不管是否nocache 都入栈，在切换页面时才能拿到当前页面，对DOM作操作
            this.stack.push({path: paths.current, view: nextPage});
          }.bind(this))
          .catch(function(err){
            console.warn("NavigationView: page [%s] not found, fail to navigate", paths.current);
            console.error(err);
          });
        }
      }
    },


  });
});
